package com.itheima.controller;

import com.itheima.commen.EnumResult;
import com.itheima.commen.R;
import com.itheima.commen.Result;
import com.itheima.dto.UserDto;
import com.itheima.pojo.User;
import com.itheima.service.FrameService;
import lombok.extern.slf4j.Slf4j;
import org.jacoco.agent.rt.internal_f3994fa.core.internal.flow.IFrame;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/frame")
public class FrameController {
    @Autowired
    private FrameService frameService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpServletResponse response;

    //用户登录  --返回值是枚举
    @PostMapping("/login")
    public R login(String username, String password) {
        R r = frameService.login(username, password);
        //登录成功,将用户的id存入session并将token的值改为登录成功
        HttpSession session = request.getSession();
        if (r.getCode() == 0) {
            User user = (User) r.getData();
            session.setAttribute("userId", user.getId());
//            session.setAttribute("token", UUID.randomUUID().toString());
            //修改token的状态为登陆成功
            log.info("登录成功");
            return r;
        }
        log.info("登录失败");
        return r;
    }

    //用户注册
    @PostMapping("/register")
    public void register(String username, String password) {
        log.info("username--" + username);
        log.info("password--" + password);
        frameService.register(username, password);
    }

    //用户修改密码
    @PostMapping("/password")
    public void password(String oldPassword, String newPassword) {
        log.info("oldPassword--" + oldPassword);
        log.info("newPassword--" + newPassword);
        frameService.password(oldPassword, newPassword);
    }

    //用户注销
    @PostMapping("/logout")
    public void logout() {
        HttpSession session = request.getSession();
//        String token = (String) session.getAttribute("token");
        Long userId = (Long) session.getAttribute("userId");
        log.info("userId==" + userId);
        if (userId!=null) {
            session.invalidate();
            log.info("注销成功");
        }
        log.info("注销失败");
    }

    //用户资料
    @PostMapping("/profile")
    public UserDto profile() throws IOException {
        HttpSession session = request.getSession();
        Long userId = (Long) session.getAttribute("userId");
        UserDto dto = frameService.profile(userId);
        return dto;
    }
}
